var Buffer = require('buffer').Buffer,
    fs     = require('fs'),
    id3v1  = require('./id3v1'),
    id3v2  = require('./id3v2'),
    id4    = require('./id4');

var getID3Version = function (buffer) {
  if (buffer.toString('binary', 0, 3) === 'ID3') {
    return 'id3v2';
  } else if ('ftypM4A' === buffer.toString('binary', 4, 11)) {
    return 'id4';
  }
  return 'id3v1';
};


var getTags = function (buffer) {
  var parser,
      version = getID3Version(buffer);

  switch (version) {
    case 'id3v1':
      return id3v1.readTags.call({
        buffer: buffer
      });
      break;
    case 'id3v2':
      return id3v2.readTags.call({
        buffer: buffer
      });
      break;
    case 'id4':
      return id4.readTags.call({
        buffer: buffer
      });
    default:
      return {};
  }
};

var cleanTags = function (buffer) {

  var aliases = {
    "title"  : ["TIT2", "TT2"],
    "artist" : ["TPE1", "TP1"],
    "album"  : ["TALB", "TAL"],
    "year"   : ["TYER", "TYE"],
    "comment": ["COMM", "COM"],
    "track"  : ["TRCK", "TRK"],
    "genre"  : ["TCON", "TCO"],
    "picture": ["APIC", "PIC"],
    "lyrics" : ["USLT", "ULT"]
  },
      clean = {},
      dirty = getTags(buffer);

  Object.keys(aliases).forEach(function (k) {
    aliases[k].forEach(function (v) {
      var tag = dirty[v];
      if (tag) {
        clean[k] = tag;
      }
    });
  });

  return clean;
}

module.exports = function (buffer) {
  var tags = cleanTags(buffer);

  Object.keys(tags).forEach(function(i) {
    tags[i] = tags[i].data;
  });

  return tags;
}
